package cn.tedu.service;

import cn.tedu.dao.TOrderDao;
import cn.tedu.entity.CartItem;
import cn.tedu.entity.TAddress;
import cn.tedu.entity.TOrder;
import cn.tedu.entity.TOrderItem;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * (TOrder)表服务接口
 *
 * @author makejava
 * @since 2021-12-23 22:02:29
 */
public class TOrderService {
    private TOrderDao orderDao = new TOrderDao();

    public TOrder createOrder(TAddress address, Map<String, CartItem> cart, int userId) {
        TOrder order = new TOrder();
        order.setOrderDesc("");
        order.setOrderTime(System.currentTimeMillis() + "");
        order.setUserId(userId);
        double totalPrice = 0;
        // 构建订单详情表
        List<TOrderItem> orderItemList = new ArrayList<>();
        for (CartItem cartItem : cart.values()) {
            TOrderItem orderItem = new TOrderItem();
            orderItem.setAmount(cartItem.getDangPrice() * cartItem.getAmount());
            orderItem.setBookId(cartItem.getId());
            orderItem.setBookName(cartItem.getBookName());
            orderItem.setBookNum(cartItem.getAmount());
            orderItem.setDangPrice(cartItem.getDangPrice());
            totalPrice = totalPrice + orderItem.getAmount();
            orderItemList.add(orderItem);
        }
        order.setTotalPrice(totalPrice);

        // 保存订单
        TOrder o = new TOrder();
        try {
            o = orderDao.createOrder(address, order, orderItemList);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return o;
    }

}
